package com.ddpt.platform.common.util.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ConverterUtils;

import java.util.*;

public abstract class AbstractReadExcelListener<E,T> extends AnalysisEventListener<T> {


    //一次最多读取的行数
    protected Integer maxReadCount = 1;

    //当前读取的数据
    protected List<E> data = new ArrayList<>();

    //头数据
    protected Map<Integer, String> headers;

    //需要跳过的行 (默认第一行是key，第二行是中文说明，第三行开始为数据行)
    protected Set<Integer> skipRow = new HashSet<>(Arrays.asList(0,1));

    //数据读取完成后的回调
    protected ExcelReaderCallBack<E> callBack = (data -> {
        System.out.println("excel数据未处理");
    });


    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        if(skipRow.contains(analysisContext.readRowHolder().getRowIndex())){
            //该行被标记跳过
            return ;
        }
        E e = parse(t);
        if(e == null){
            return ;
        }
        if(maxReadCount == 1){
            callBack.callBack(Collections.singletonList(e));
            return ;
        }
        data.add(e);
        if(data.size() >= maxReadCount){
            callBack.callBack(data);
            data.clear();
        }
    }

    protected E parse(T t){
        return (E) t;
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        headers = ConverterUtils.convertToStringMap(headMap, context);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        callBack.callBack(data);
        data.clear();
    }

    public void setSkipRow(Set<Integer> skipRow) {
        this.skipRow = skipRow;
    }
}
